//
//  SelectColorView.m
//  LYPhotos
//
//  Created by 美鑫科技 on 16/5/17.
//  Copyright © 2016年 MorpLCP. All rights reserved.
//

#import "CPSelectColorView.h"

@interface CPSelectColorView ()

@property (nonatomic, strong) UIImageView *colorImageView;
@property (nonatomic, strong) UIImageView *ballView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation CPSelectColorView

#define kBtn_width 50
#define kBtn_borderWith  2
#define kBtn_cornerRadius 10
#define kBtn_titleColor RGBCOLOR(255,255,255)
#define kBtn_borderColor RGBCOLOR(255,255,255).CGColor
#define kCleanColor [UIColor clearColor]
#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
#define COLOR_RGB(rgbValue) [UIColor colorWith\
Red     :(rgbValue & 0xFF0000)     / (float)0xFF0000 \
green   :(rgbValue & 0xFF00)       / (float)0xFF00 \
blue    :(rgbValue & 0xFF)         / (float)0xFF \
alpha   :1.0]

- (instancetype)init{
    self = [super init];
    if (self) {
        self.frame = [UIScreen mainScreen].bounds;
        self.backgroundColor = kCleanColor;
        [self setSubViews];
    }
    return self;
}

- (void)setSubViews{
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 64)];
    self.topView.backgroundColor = [ThemeManager shareManager].theme.themeColor;
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 49, self.frame.size.width, 49)];
    self.bottomView.backgroundColor = [ThemeManager shareManager].theme.themeColor;
    
    self.colorImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (self.frame.size.height - self.frame.size.width) / 2.0, self.frame.size.width, self.frame.size.width)];
    self.colorImageView.backgroundColor = kCleanColor;
    self.colorImageView.image = [LYImage imageNamed:@"selectColor"];
    self.colorImageView.userInteractionEnabled = YES;
    
    self.ballView = [UIImageView new];
    self.ballView.layer.borderWidth = 1;
    self.ballView.layer.borderColor = [UIColor grayColor].CGColor;
    self.ballView.backgroundColor = kCleanColor;
    self.ballView.frame = CGRectMake(0, 0, 5, 5);
    
    [self.colorImageView addSubview:self.ballView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)];
    [self.colorImageView addGestureRecognizer:pan];
    [self.colorImageView addGestureRecognizer:tap];
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    backView.backgroundColor = [COLOR_RGB(0x000000) colorWithAlphaComponent:0.7];
    [self addSubview:backView];
    [self addSubview:self.colorImageView];
    [self addSubview:self.topView];
    [self addSubview:self.bottomView];
    
    UIButton *btnClose = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btnClose setTitleColor:kBtn_titleColor forState:(UIControlStateNormal)];
    [btnClose setTitle:@"X" forState:(UIControlStateNormal)];
    btnClose.frame = CGRectMake(self.frame.size.width - kBtn_width, 65, kBtn_width, kBtn_width);
    [btnClose setBackgroundColor:[UIColor grayColor]];
    [backView addSubview:btnClose];
    [btnClose addTarget:self action:@selector(dismiss) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *btnSure = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btnSure setTitleColor:kBtn_titleColor forState:(UIControlStateNormal)];
    [btnSure setTitle:@"确认" forState:(UIControlStateNormal)];
    btnSure.layer.masksToBounds = YES;
    btnSure.layer.borderWidth = kBtn_borderWith;
    btnSure.layer.borderColor = kBtn_borderColor;
    btnSure.layer.cornerRadius = kBtn_cornerRadius;
    btnSure.frame = CGRectMake((self.frame.size.width - 200) / 2.0, (self.frame.size.height - 49 - 40 - 10), 200, 40);
    [btnSure setBackgroundColor:kCleanColor];
    [backView addSubview:btnSure];
    [btnSure addTarget:self action:@selector(changeThemeAction) forControlEvents:(UIControlEventTouchUpInside)];
    
}

// 改变主题颜色
- (void)changeThemeAction{
    [[ThemeManager shareManager] changeThemeWithColor:self.topView.backgroundColor];
    [self dismiss];
}

// 点选
- (void)tapAction:(UITapGestureRecognizer *)sender{
    
    CGPoint point = [sender locationInView:self.colorImageView];
    CGPoint newPoint = {(self.colorImageView.image.size.width / self.colorImageView.frame.size.width) * point.x, (self.colorImageView.image.size.height / self.colorImageView.frame.size.height) * point.y};
    // 控制选择区域不超出圆形区域
    CGFloat distance = [self getLengthWithPoint:point CenterPoint:CGPointMake(CGRectGetMidX(self.colorImageView.bounds), CGRectGetMidY(self.colorImageView.bounds))];
    if (distance > (self.colorImageView.frame.size.width / 2.0)) {
        return;
    }
    self.ballView.center = point;
    UIColor *themeColor = [self getPiexColorWithPoint:newPoint];
    self.topView.backgroundColor = themeColor;
    self.bottomView.backgroundColor = themeColor;
    
}

// 托选
- (void)panView:(UIPanGestureRecognizer *)sender{
    
    CGPoint point = [sender locationInView:self.colorImageView];
    CGPoint newPoint = {(self.colorImageView.image.size.width / self.colorImageView.frame.size.width) * point.x, (self.colorImageView.image.size.height / self.colorImageView.frame.size.height) * point.y};
    // 控制选择区域不超出圆形区域
    CGFloat distance = [self getLengthWithPoint:point CenterPoint:CGPointMake(CGRectGetMidX(self.colorImageView.bounds), CGRectGetMidY(self.colorImageView.bounds))];
    if (distance > (self.colorImageView.frame.size.width / 2.0)) {
        return;
    }
    self.ballView.center = point;
    UIColor *themeColor = [self getPiexColorWithPoint:newPoint];
    self.topView.backgroundColor = themeColor;
    self.bottomView.backgroundColor = themeColor;
    
}

- (UIColor *)getPiexColorWithPoint:(CGPoint)point{
    
    UIColor *color = nil;
    CGImageRef imgRef = self.colorImageView.image.CGImage;
    CGContextRef cgcRef = [self createARGBBitmapContextFromImage:imgRef];
    if (cgcRef == NULL)return nil;
    size_t width = CGImageGetWidth(imgRef);
    size_t height = CGImageGetHeight(imgRef);
    CGRect rect = {{0,0},{width,height}};
    CGContextDrawImage(cgcRef, rect, imgRef);
    
    unsigned char* data = CGBitmapContextGetData (cgcRef);
    if (data != NULL) {
        @try {
            int offset = 4*((width*round(point.y))+round(point.x));
            int alpha =  data[offset];
            int red = data[offset+1];
            int green = data[offset+2];
            int blue = data[offset+3];
            color = [RGBCOLOR(red, green, blue) colorWithAlphaComponent:alpha];
        }
        @catch (NSException * e) {
            NSLog(@"%@",[e reason]);
        }
        @finally {
        }
    }
    CGContextRelease(cgcRef);
    if (data) free(data);
    return color;
    
}

// 创建取色区域
- (CGContextRef)createARGBBitmapContextFromImage:(CGImageRef)imgRef {
    
    CGContextRef context = NULL;
    CGColorSpaceRef colorSpace;
    void * bitmapData;
    unsigned long bitmapByteCount;
    unsigned long bitmapBytesPerRow;
    size_t width = CGImageGetWidth(imgRef);
    size_t height = CGImageGetHeight(imgRef);
    bitmapBytesPerRow = (width * 4);
    bitmapByteCount = (bitmapBytesPerRow * height);
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL){
        fprintf(stderr, "错误的取色区域");
        return NULL;
    }
    
    bitmapData = malloc(bitmapByteCount);
    if (bitmapData == NULL){
        fprintf (stderr, "未分配内存");
        CGColorSpaceRelease(colorSpace);
        return NULL;
    }
    
    context = CGBitmapContextCreate (bitmapData,
                                     width,
                                     height,
                                     8,
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedFirst);
    if (context == NULL){
        free (bitmapData);
        fprintf (stderr, "未创建上下文");
    }
    CGColorSpaceRelease(colorSpace);
    return context;
    
}

// 求两点的距离
- (CGFloat)getLengthWithPoint:(CGPoint)point CenterPoint:(CGPoint)centerPoint{
    CGFloat length = sqrtf((point.x - centerPoint.x) * (point.x - centerPoint.x) + (point.y - centerPoint.y) * (point.y - centerPoint.y));
    return length;
}

- (void)show{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];
}
- (void)dismiss{
    [self removeFromSuperview];
}

@end
